package com.future.baselib.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.future.baselib.entity.RongResponse;
import com.future.baselib.inteface.HttpService;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;


/**
 * Created by jniu on 2017/6/20.
 */

public class RongRequest<T extends RongResponse> {

    public static final String TAG = RongRequest.class.getName();


    private static HttpService httpService;

    private static int readTimeout = 5;
    private static int writeTimeout = 60;

    private Context context;
    private String url = "/user/getToken.json";
    private TreeMap<String, Object> params;


    private OnNetworkListener<T> listener;

    public static HttpService getHttpService() {
        if (httpService == null) {
            httpService = initRetrofit();
        }
        return httpService;
    }

    private static HttpService initRetrofit() {
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder()
                .connectTimeout(readTimeout, TimeUnit.SECONDS)
                .writeTimeout(writeTimeout, TimeUnit.SECONDS)
                .readTimeout(readTimeout, TimeUnit.SECONDS);

        httpClient.addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                //App Secret、Nonce (随机数)、Timestamp (时间戳)三个字符串按先后顺序拼接成一个字符串并进行 SHA1 哈希计算
                String AppKey = "c9kqb3rdcofkj";
                String Nonce = StringUtils.getRandomNum(10);
                String Timestamp = String.valueOf(DateUtils.getTimeMillis());
                Timestamp = Timestamp.substring(0, Timestamp.length() - 3);

                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("BggrnrMVDf");
                stringBuilder.append(Nonce);
                stringBuilder.append(Timestamp);
                String Signature = "";
                try {
                    Signature = MD5.sha1(stringBuilder.toString());
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }

                Request original = chain.request();
                Request request = original.newBuilder()
                        .header("App-Key", AppKey)
                        .header("Nonce", Nonce)
                        .header("Timestamp", Timestamp)
                        .header("Signature", Signature)
                        .method(original.method(), original.body())
                        .build();
                return chain.proceed(request);
            }
        });

        OkHttpClient client = httpClient.build();
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://api.cn.ronghub.com")
                .addConverterFactory(ScalarsConverterFactory.create())
                .client(client)
                .build();

        return retrofit.create(HttpService.class);
    }

    public RongRequest setTimeout(int readTimeout, int writeTimeout) {
        this.readTimeout = readTimeout;
        this.writeTimeout = writeTimeout;
        return this;
    }


    public RongRequest with(Context context) {
        this.context = context;
        return this;
    }

    public RongRequest put(String key, String values) {
        if (params == null)
            params = new TreeMap<>();
        params.put(key, values);
        return this;
    }


    public RongRequest setListener(OnNetworkListener listener) {
        this.listener = listener;
        return this;
    }

    public RongRequest start(final T t) {
        if (context == null) {
            LogUtils.e(TAG, "context不能为空");
            return this;
        }

        if (listener == null) {
            LogUtils.e(TAG, "请添加网络结果监听 Listener");
            return this;
        }

        if (checkNetworkStatus()) {
            Call<String> call = getHttpService().getData(RongRequest.this.params, url);
            call.enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, Response<String> response) {
                    t.parseJson(response.body(), response.code());
                    if (t.returnNo == 200) {
                        listener.onSuccess(t.token);
                    } else {
                        listener.onFail(t.erroMessage);
                    }
                }

                @Override
                public void onFailure(Call<String> call, Throwable t) {
                    listener.onFail(t.getMessage());
                }
            });
        } else {
            listener.onFail("当前无网络连接，请检查网络后重试");
        }


        return this;
    }


    /**
     * 检查网络状态
     *
     * @return
     */
    public boolean checkNetworkStatus() {
        ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        Boolean isWifiConn = networkInfo.isConnected();

        networkInfo = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        Boolean isMobileConn = networkInfo.isConnected();

        return isMobileConn || isWifiConn;
    }

    public interface OnNetworkListener<T extends RongResponse> {
        void onSuccess(String token);

        void onFail(String message);
    }
}
